import os
from flask import Blueprint, request, render_template, jsonify, current_app
from applications.common import curd
from applications.common.curd import enable_status, disable_status
from applications.common.utils.http import fail_api, success_api, table_api
from applications.common.utils.rights import authorize

from flask_login import current_user
from applications.common.curd import model_to_dicts
from applications.common.helper import ModelFilter
from applications.common.utils.validate import str_escape
from applications.extensions import db
from applications.models import Role, Dept
from applications.models import User, AdminLog
from applications.models import Settings_web
from applications.schemas import Settings_webOutSchema


bp = Blueprint('site', __name__, url_prefix='/site')




#  网站基本设置
@bp.get('/')
@authorize("system:site:main")
def main():
    # 初始化数据库-取消注释，执行一次即可
    # db.create_all()
    # settings_data = Settings_web(id=2,key_name="my_key", value_name="my_value", remark="测试", enable=1)  
    # settings_data = [
    #     Settings_web(
    #         id=1,
    #         key_name='sitename',
    #         value_name='管理员',
    #         remark='网站名称',
    #         enable=1,
    #     ),
    #     Settings_web(
    #         id=2,
    #         key_name='icpbeian',
    #         value_name='ICP备案号',
    #         remark='ICP备案号',
    #         enable=1,
    #     ),
    #     Settings_web(
    #         id=3,
    #         key_name='icon_href',
    #         value_name='/static/system/admin/images/logo.png',
    #         remark='图标',
    #         enable=1,
    #     ),
    #     Settings_web(
    #         id=4,
    #         key_name='logo_href',
    #         value_name='/static/system/admin/images/logo.png',
    #         remark='标志LOGO',
    #         enable=1,
    #     ),

    # ]   
    # db.session.add_all(settings_data)
    # db.session.commit() 

    return render_template('/system/settings/main.html')

#  查询数据
@bp.get('/table')
@authorize("system:site:main")
def data():
    # site =Settings_web.query.filter().all()
    # 查询参数构造
    mf = ModelFilter()
    site = Settings_web.query.filter(mf.get_filter(Settings_web)).layui_paginate()
    count = site.total
    # 返回api
    return table_api(data=model_to_dicts(schema=Settings_webOutSchema, data=site.items), count=count)

@bp.route('/query', methods=['POST','GET'])
@authorize("system:site:main", log=True)
def query():
    
    if request.method == 'GET':
        selectname = request.args.get('selectname')
    if request.method == 'POST':
        data = request.get_json()
        selectname = data.get('selectname')
    # 查询参数构造
    mf = ModelFilter()
    if selectname == None or selectname =='':
        # 查询数据库表名称filename的filename字段及数据
        query = Settings_web.query.filter(mf.get_filter(Settings_web)).layui_paginate()
        count = query.total
    else:
        # 模糊查询数据库表中字段name、card、password、uid的数据包含selectname的结果
        query = Settings_web.query.filter(mf.get_filter(Settings_web)).filter(Settings_web.key_name.like(f'%{selectname}%')|Settings_web.value_name.like(f'%{selectname}%')|Settings_web.remark.like(f'%{selectname}%')).layui_paginate()
        count = query.total
    
    data = model_to_dicts(schema=Settings_webOutSchema, data=query.items)
    # print(data)
    # 返回api
    return table_api(msg="成功",data=data, count=count)

# 用户增加
@bp.get('/add')
@authorize("system:site:add", log=True)
def add():
    return render_template('system/settings/add.html')

@bp.route('/save', methods=['post'])
@authorize("system:site:add", log=True)
def save():
    data = request.get_json()
    key_name = data.get('key_name')
    value_name = data.get('value_name')
    remark = data.get('remark')
    enable = data.get('enable')
    # print(key_name, value_name, remark)
    # 插入数据
    res_web = Settings_web.query.filter_by(key_name=key_name).first()
    if res_web: return fail_api(msg="该参数已存在")
    res_web = Settings_web(key_name=key_name, value_name=value_name, remark=remark,enable=enable)
    db.session.add(res_web)
    db.session.commit()
    return success_api(msg="增加成功")

#  编辑参数
@bp.route('/edit', methods=['post','get'])
@authorize("system:site:edit", log=True)
def edit():
    id = request.args.get('id')
    webdata = Settings_web.query.filter_by(id=id).first()
    # print(webdata.key_name, webdata.value_name, webdata.remark)
    return render_template('system/settings/edit.html', webdata=webdata)

#  编辑用户
@bp.route('/update', methods=['post','get'])
@authorize("system:site:edit", log=True)
def update():
    data = request.get_json()
    id = data.get('id')
    key_name = data.get('key_name')
    value_name = data.get('value_name')
    remark = data.get('remark')
    enable = data.get('enable')
    res = Settings_web.query.filter_by(id=id).update({'key_name':key_name,'value_name':value_name,'remark':remark,'enable':enable})
    if not res: 
        return fail_api(msg="更新失败")
    db.session.commit()
    return success_api(msg="更新成功")
    


#    参数删除
# @bp.route('/remove/<int:id>', methods=['DELETE'])
@bp.route('/remove', methods=['post'])
@authorize("system:site:remove", log=True)
def delete():
    key_name = request.form.get('key_name')
    res = Settings_web.query.filter_by(key_name=key_name).delete()
    if not res:
        return fail_api(msg="删除失败")
    db.session.commit()
    return success_api(msg="删除成功")

# 批量删除
@bp.route('/batchRemove', methods=['post'])
@authorize("system:site:remove", log=True)
def batch_remove():
    ids = request.form.getlist('ids[]')
    for id in ids:
        res = Settings_web.query.filter_by(id=id).delete()
        if not res:
            return fail_api(msg="批量删除失败")
    db.session.commit()
    return success_api(msg="批量删除成功")